//SERVER!!SERVER!!SERVER!!SERVER!!SERVER!!SERVER!!SERVER!!SERVER!!SERVER!!SERVER!!
//SERVER!!SERVER!!SERVER!!SERVER!!SERVER!!SERVER!!SERVER!!SERVER!!SERVER!!SERVER!!

#include <iostream>
#include <string>
#include <SDL_net.h>
#undef main

#include <assert.h>
#include "../Library/ServerSocket.h"
#include "GMGetPlayerTurn.h"

#define MAX_LENGTH 2000

int main(int argc, char** argv)
{
	SDL_Init(0);
	SDLNet_Init();

	std::cout<<"SERVER\n";

	
	ServerSocket ListenSock;
	if(argc<3)
	{
		std::cout<<"Arguments missing \n please use format: port numOfClients";
		return 0;
	}

	int port = atoi(argv[1]);
	int numOfClients=atoi(argv[2]);
	TheServer::Instance()->Open(port,numOfClients);
	std::cout<<"Opening..\n";
	if(ListenSock.ServerOpen(port))
	{
		std::cout<<"Ip: "<<ListenSock.GetIp()<<"\n";
		std::cout<<"Port: "<<ListenSock.GetPort()<<"\n";
	}
	else
	{
		ListenSock.Close();
	}

	

	std::cout<<"Connecting";

/*#ifdef _DEBUG
	int numOfClients =1;
	Socket* InSocks[1] ={0};
#endif*/

	
	Socket** InSocks = new Socket*[numOfClients];
	for (unsigned int i=0;i<numOfClients;++i)
	{
		InSocks[i]=0;
	}


	int currentClient=0;
	while (currentClient < numOfClients)

	{
		while(!InSocks[currentClient])
		{
			std::cout<<".";

			InSocks[currentClient] = ListenSock.Accept();

			SDL_Delay(1000);
		}
		currentClient++;
		std::cout<<"\nClient "<<currentClient<<" Connected!\n";

	}

	std::cout<<"All Clients Connected!\n";

	currentClient =0;

	SockMessage OutMsg;
	GameMessage* ballRolling;
	ballRolling=new GMGetPlayerTurn;
	ballRolling->Write(&OutMsg);

	InSocks[currentClient]->Send(OutMsg);

	SockMessage InMsg;
	while(true)
	{
		
		SockMessage InMsg;
		if(InSocks[currentClient]->Recv(&InMsg))

		{
			GameMessage* gm=0;
			gm = gm->Read(&InMsg);

			if (gm)
			{
				gm->Execute();
			}
		

			currentClient++;
			if(currentClient>numOfClients)
			{
				currentClient=0;
			}
		}
	}

	

	system("pause");
}